﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Linq.Expressions;

namespace ExpressionSerialization
{
  [KnownType(typeof(XConstantExpression))]
  [KnownType(typeof(XParameterExpressionList))]
  [DataContract]
  public class XLambdaExpression : XExpression
  {

    [DataMember]
    public XExpression Body{get; set; }

    [DataMember]
    public XParameterExpressionList Parameters {get; set; }

    public override void FromExpression(Expression source_)
    {
      base.FromExpression(source_);
      LambdaExpression exp = source_ as LambdaExpression;
      Body = XExpression.CreateFromExpression(exp.Body);
      Parameters = new XParameterExpressionList(exp.Parameters);
      //Todo: Namam ošetřený returnType
    }


    public override Expression ToExpression(Type dataContract_, System.Collections.Generic.List<ParameterExpression> parameters_)
    {
      Expression body = Body.ToExpression(dataContract_,parameters_);
      List<ParameterExpression> parameters = Parameters.ToParameterExpressionsList(dataContract_,parameters_);

      var res = Expression.Lambda(GetExpressionType(dataContract_), body, parameters);
      return res;
      /*
      var bodyParameters = from edX in body.Nodes()
                           where edX is ParameterExpression
                           select edX;
      for(int i = 0; i < parameters.Count; i++) {
        var matchingParm = from parm in bodyParameters
                           where (parm as ParameterExpression).Name == parameters[i].Name
                              && (parm as ParameterExpression).Type == parameters[i].Type
                           select parm as ParameterExpression;
        if(matchingParm.Count<ParameterExpression>() == 1)
          parameters[i] = matchingParm.First<ParameterExpression>() as ParameterExpression;
      }
      */

    }
  }
}
